package com.sgcc.nfc.lock.presentation.home

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.snackbar.Snackbar
import com.sgcc.nfc.lock.R
import com.sgcc.nfc.lock.databinding.FragmentHomeBinding
import com.sgcc.nfc.lock.domain.model.Warning
import com.sgcc.nfc.lock.presentation.nfc.NfcOperationActivity
import com.sgcc.nfc.lock.presentation.nfc.NfcOperationViewModel
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class HomeFragment : Fragment() {

    private var _binding: FragmentHomeBinding? = null
    private val binding get() = _binding!!
    private val viewModel: HomeViewModel by viewModels()
    private val warningAdapter = WarningAdapter(::onWarningClicked)

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentHomeBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setupRecycler()
        setupListeners()
        observeViewModel()
    }

    private fun setupRecycler() {
        binding.warningRecycler.apply {
            layoutManager = LinearLayoutManager(requireContext())
            adapter = warningAdapter
        }
    }

    private fun setupListeners() {
        binding.swipeRefresh.setOnRefreshListener {
            viewModel.refresh()
        }
        binding.quickNfcOpen.setOnClickListener {
            navigateToNfc(NfcOperationViewModel.Mode.OPEN)
        }
        
        binding.quickNfcClose.setOnClickListener {
            navigateToNfc(NfcOperationViewModel.Mode.CLOSE)
        }
        binding.quickWarnings.setOnClickListener {
            findNavController().navigate(R.id.warningsFragment)
        }
        binding.quickLogs.setOnClickListener {
            findNavController().navigate(R.id.logsFragment)
        }
    }

    private fun observeViewModel() {
        viewModel.stats.observe(viewLifecycleOwner) { stats ->
            val placeholder = getString(R.string.dashboard_stats_placeholder)
            if (stats != null) {
                // 绑定锁具总数卡片
                binding.locksTotalValueText.text = stats.totalLocks.value.toString()
                
                // 绑定开启中卡片
                binding.locksOpenValueText.text = stats.openLocks.value.toString()
                
                // 绑定已关闭卡片
                binding.locksClosedValueText.text = stats.closedLocks.value.toString()
                
                // 绑定待处理警告卡片
                binding.warningsPendingValueText.text = stats.pendingWarnings.value.toString()
                
                // 绑定配电房总数卡片
                binding.roomsTotalValueText.text = stats.totalRooms.value.toString()
                
                // 绑定今日操作卡片
                binding.operationsTodayValueText.text = stats.todayOperations.value.toString()
            } else {
                binding.locksTotalValueText.text = placeholder
                binding.locksOpenValueText.text = placeholder
                binding.locksClosedValueText.text = placeholder
                binding.warningsPendingValueText.text = placeholder
                binding.roomsTotalValueText.text = placeholder
                binding.operationsTodayValueText.text = placeholder
            }
        }
        viewModel.warnings.observe(viewLifecycleOwner) { warnings ->
            warningAdapter.submitList(warnings)
        }
        viewModel.isLoading.observe(viewLifecycleOwner) { loading ->
            binding.swipeRefresh.isRefreshing = loading
        }
        viewModel.error.observe(viewLifecycleOwner) { error ->
            error?.let {
                Snackbar.make(binding.root, it, Snackbar.LENGTH_LONG).show()
            }
        }
    }





    private fun navigateToNfc(mode: NfcOperationViewModel.Mode, password: String = "123456") {
        android.util.Log.d("HomeFragment", "Navigating to NFC with mode: $mode, password: $password")
        val intent = NfcOperationActivity.createIntent(requireContext(), mode = mode, password = password)
        startActivity(intent)
    }

    private fun onWarningClicked(warning: Warning) {
        val action = R.id.warningDetailFragment
        findNavController().navigate(action, Bundle().apply {
            putLong("warningId", warning.warningId)
        })
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}


